package cloud.keveri.response4j;

import cloud.keveri.base.DefaultResponse;
import cloud.keveri.base.KeveriException;
import cloud.keveri.base.result.Response;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import static cloud.keveri.response4j.Response4jErrorCodeConstants.RESPONSE4J_ERROR;
import static cloud.keveri.response4j.Response4jErrorCodeConstants.STYLE_NOT_FOUND;
import static cloud.keveri.response4j.def.Const.Default;

/**
 * <p>
 * 作者：沈自在
 **/
@Getter
public class ResponseManager {

    /**
     *
     */
    private final Class<?> responseClazz;

    public ResponseManager(String style) {
        responseClazz = deduceResponseClazz(style);
    }

    /**
     * 生成空对象
     */
    public Response buildEmptyResponse() {
        try {
            return (Response) responseClazz.getConstructor().newInstance();
        } catch (Exception ex) {
            throw new KeveriException(RESPONSE4J_ERROR);
        }
    }

    private Class<?> deduceResponseClazz(String style) {
        // 1. 默认配置
        if (StringUtils.isBlank(style) || style.equals(Default)) {
            return DefaultResponse.class;
        }

        // 2. 自定义配置
        try {
            return Class.forName(style);
        } catch (Exception e) {
            throw new KeveriException(STYLE_NOT_FOUND);
        }
    }
}
